package com.philip.demo;

import org.bytedeco.javacpp.Loader;
import org.bytedeco.opencv.opencv_core.*;
import org.bytedeco.opencv.opencv_objdetect.CascadeClassifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import static org.bytedeco.opencv.global.opencv_imgproc.rectangle;

/**
 * 人脸检测
 * 用于发现视频中的人脸并进行标记
 */
public class P_FaceDetect {

    private static final Logger LOGGER = LoggerFactory.getLogger(P_FaceDetect.class);

    CascadeClassifier faceDetector;

    public P_FaceDetect() throws IOException {
        URL haarcascadeUrl = getClass().getClassLoader().getResource("haarcascade_frontalface_alt.xml");
        File file = Loader.cacheResource(haarcascadeUrl);
        String classifierName = file.getAbsolutePath();
        faceDetector = new CascadeClassifier(classifierName);
    }

    /**
     * 发现人脸
     * @param grayImage 當前幀的圖像對象
     * @return 返回監測的所有的人臉對象數組
     * @throws Exception
     */
    public Rect[] detectFace(Mat grayImage ,Mat grabbedImage) throws Exception {
        LOGGER.info("Running DetectFace ... ");

        RectVector faces = new RectVector();
        LOGGER.info("人脸检测中...");
        faceDetector.detectMultiScale(grayImage,faces);
        long total = faces.size();
        LOGGER.info("Detected {} faces",total);
        Rect[] rects = faces.get();
        if (rects !=null && rects.length>=1){
            for (Rect rect : rects) {
                markRectangle(grabbedImage,rect);
            }
        }
//        faceDetector.close();
        return  rects;
    }

    /**
     * 标记检测到的人脸
     */
   private void markRectangle(Mat originalImage, Rect rect) {
       rectangle(originalImage,rect, Scalar.GREEN);
   }
}
